#include "model.h"

S::S() {
  memset(this, '\0', sizeof(*this)); 
}

S::S(const char* name, int age, double weight, double height) {
  strncpy(this->name, name, sizeof(this->name));
  this->age = age;
  this->weight = weight;
  this->height = height;
}

void load_data(S* d) 
{
  d[0] = S("Andrjusha", 39, 200.0, 180.0);
  d[1] = S("Ira", 36, 110.0, 165.0);
  d[2] = S("David", 9, 80.0, 148.0);
  d[3] = S("Danja", 4, 40, 104.0);
};

STableModel::STableModel(size_t nof_rows, S* d) 
{
  this->nof_rows = nof_rows;
  this->rows = d;
}

void STableModel::grow() 
{
  for (int i = 0; i < 4; i++) {
    this->rows[i].height += 0.01;
    QModelIndex mindex = this->index(i, 3);
    emit dataChanged(mindex, mindex);
  }
}

  // Qt
int STableModel::rowCount(const QModelIndex&) const { 
  return this->nof_rows; 
}
int STableModel::columnCount(const QModelIndex&) const { 
  return 4; 
}

QVariant STableModel::data(const QModelIndex& index, int role) const 
{ 
  if (!index.isValid()) {
    return QVariant(); 
  }
  if (role != Qt::DisplayRole) {
    return QVariant();
  }
  int row_index = index.row();
  int col_index = index.column();
  
  QVariant ret;
  S* r = &rows[row_index];
  char v_buf[256];
  if (col_index == 0) { strncpy(v_buf, r->name, sizeof(v_buf)); }
  if (col_index == 1) { sprintf(v_buf, "%d", r->age); }
  if (col_index == 2) { sprintf(v_buf, "%f", r->weight); }
  if (col_index == 3) { sprintf(v_buf, "%f", r->height); }
  ret = v_buf;
  return ret;
}

QVariant 
STableModel::headerData(int section, Qt::Orientation orientation,int role) const 
{ 
  if (role != Qt::DisplayRole) {
    return QVariant();
  }
  
  QVariant ret;
  char v_buf[256];
  if (orientation == Qt::Horizontal) {      
    //sprintf(v_buf, "col%d", section);
    if (section == 0) strncpy(v_buf, "name", sizeof(v_buf));
    if (section == 1) strncpy(v_buf, "age", sizeof(v_buf));
    if (section == 2) strncpy(v_buf, "weight", sizeof(v_buf));
    if (section == 3) strncpy(v_buf, "height", sizeof(v_buf));
  } else if (orientation == Qt::Vertical) {
    sprintf(v_buf, "row%d", section);
  }
  ret = v_buf;
  
  return ret;
}

RefreshTimer::RefreshTimer(QObject* parent, QTableView* t, STableModel* m) : 
  QTimer(parent)
{
  this->t = t;
  this->m = m;
  connect(this, SIGNAL(timeout()), this, SLOT(timeout()));
}

void RefreshTimer::timeout() 
{
  cerr << "timeout" << endl;
  m->grow();
}
